using Auth.Domain.Entities;
using Auth.Infrastructure.Repositories;
using AutoMapper;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using Warehouse.Application.Dto.Input;
using Warehouse.Application.Dto.Output;
using Warehouse.Domain.Entities;
using Warehouse.Infrastructure.Repositories;
using Warehouse.Result;
using Yitter.IdGenerator;

namespace Warehouse.Application.Services.Warehouse
{
    public class WarehouseModelAppService : IWarehouseModelAppService 
    {
        
        private readonly IMapper _mapper;
        private readonly IWarehouseModelRepository<WareHouseModel> _warehouseModelRepository;
        private readonly IWarehouseModelRepository<MoIdModel> _moidModelRepository;
        private readonly IAuthRepository<UserModel> _userModelRepository;

        private readonly ILogger<WarehouseModelAppService> _logger;





        public WarehouseModelAppService(IMapper mapper, IWarehouseModelRepository<WareHouseModel> warehouseModelRepository, IWarehouseModelRepository<MoIdModel> moidModelRepository, ILogger<WarehouseModelAppService> logger, IAuthRepository<UserModel> userModelRepository)
        {

            _mapper = mapper;
            _warehouseModelRepository = warehouseModelRepository;
            _moidModelRepository = moidModelRepository;
            _logger = logger;
            _userModelRepository = userModelRepository;
        }



        /// <summary>
        /// 添加仓库
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public  ApiResult<int> CreateWareHouse(CreateWareHouseInput input)
        {
            var model = _mapper.Map<WareHouseModel>(input);
            model.Id = YitIdHelper.NextId();
            model.CreatedAt = DateTime.Now.Date;
            model.IsDeleted = false;

            // 获取当前日期并格式化为yyyyMMdd
            string dateStr = DateTime.Now.ToString("yyyyMMdd");

            // 查询当天已有的记录数
            string prefix = "MD" + dateStr;
            var todayItems = _warehouseModelRepository.GetValue()
                .Where(x => x.WareHouseCoding != null &&
                            x.WareHouseCoding.StartsWith(prefix) &&
                            x.CreatedAt.Date == DateTime.Now.Date)
                .ToList();

            // 计算序号
            int sequence = todayItems.Count + 1;

            // 生成编码
            string coding = $"{prefix}{sequence:D4}";
            model.WareHouseCoding = coding;


            _warehouseModelRepository.Create(model);
            _logger.LogInformation("添加仓库:" + model.Id);
            return new ApiResult<int>()
            {
                Code = ApiEnum.Ok,
                Message = "创建成功",
                Data = 1
            };
        }



        /// <summary>
        /// 获取仓库列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
       public ApiPaing<ListWareHouseOutput> GetWareHouse(PageInput input)
       {
            var list = _warehouseModelRepository.GetValue().Where(x => x.IsDeleted == false);
            var moid = _moidModelRepository.GetValue().Where(x => x.IsDeleted == false);
            var use =_userModelRepository.GetAll().Where(x => x.IsDeleted == false);
            var linq = from x in list
                       join
                      y in moid on x.WareHouseStatus equals y.Id
                      join z in use on x.Loginname equals z.Id
                       select new ListWareHouseOutput()
                       {
                           Id = x.Id,
                           WareHouseCoding = x.WareHouseCoding,
                           WareHouseName = x.WareHouseName,
                           WareHouseStatus = x.WareHouseStatus,
                           Loginid = x.Loginname,
                           loginName=y.MoIdName,
                           WareHouseAddress = x.WareHouseAddress,
                           WareHouseDescribe = x.WareHouseDescribe,
                           CreatedBy = x.CreatedBy,
                           CreatedAt = x.CreatedAt,
                           loginMC = z.RealName
                           
                       };
            var model =linq.OrderByDescending(x => x.Id).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();

            return new ApiPaing<ListWareHouseOutput>
            {
                TotalCount = list.Count(),
                PageDatas = model,
                Code = ApiEnum.Ok,
                Message = "成功"
            };
       }


        /// <summary>
        /// 逻辑删除仓库信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> DeleteWareHouse(long Id)
        {
            var list =_warehouseModelRepository.GetValue().FirstOrDefault(x=>x.Id==Id && x.IsDeleted ==false);
            if (list==null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Fail,
                    Message = "未找到仓库"
                };
            }
            list.IsDeleted = true;
            _warehouseModelRepository.Update(list);
            _logger.LogError("删除仓库：" + Id);
            return new ApiResult<int>
            {
                Code = ApiEnum.Ok,
                Message = "删除成功",
                Data = 1
            };

        }

        /// <summary>
        /// 修改仓库信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateWareHouse(UpdateWareHouseInput input)
        {
            var list = _warehouseModelRepository.GetValue().FirstOrDefault(x => x.Id == input.Id);
            if (list == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Fail,
                    Message = "未找到仓库"
                };
            }
            var model = _mapper.Map(input, list);
            model.UpdatedAt = DateTime.Now;
            _warehouseModelRepository.Update(model);
            return new ApiResult<int>
            {
                Code = ApiEnum.Ok,
                Message = "修改成功",
                Data =1
            };
        }


        /// <summary>
        /// 获取仓库信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<WareHouseModel> GetModelWareHouse(long Id)
        {
            var list = _warehouseModelRepository.GetValue().FirstOrDefault(x => x.Id == Id && x.IsDeleted == false);
            if (list == null)
            {
                return new ApiResult<WareHouseModel>
                {
                    Code = ApiEnum.Fail,
                    Message = "未找到仓库"
                };
            }
            return new ApiResult<WareHouseModel>
            {
                Code = ApiEnum.Ok,
                Message = "成功",
                Data = list
            };
        }



        /// <summary>
        /// 获取仓库列表
        /// </summary>
        /// <returns></returns>
        public ApiPaing<MoIdModel> GetMoid()
        {
            var list = _moidModelRepository.GetValue().Where(x=>x.IsDeleted==false);
            return new ApiPaing<MoIdModel>
            {
                Code= ApiEnum.Ok,
                TotalCount = list.Count(),
                PageDatas = list.ToList()
            };
        }

        /// <summary>
        /// 生成仓库编码 格式为MD+年月日+序号(如MD202506300001)
        /// </summary>
        /// <returns>生成的编码</returns>
        public string GenerateWareHouseCoding()
        {
            // 获取当前日期并格式化为yyyyMMdd
            string dateStr = DateTime.Now.ToString("yyyyMMdd");
            
            // 查询当天已有的记录数
            string prefix = "MD" + dateStr;
            var todayItems = _warehouseModelRepository.GetValue()
                .Where(x => x.WareHouseCoding != null && 
                            x.WareHouseCoding.StartsWith(prefix) && 
                            x.CreatedAt.Date == DateTime.Now.Date)
                .ToList();
            
            // 计算序号
            int sequence = todayItems.Count + 1;
            
            // 生成编码
            string coding = $"{prefix}{sequence:D4}";
            
            return coding;
        }




    }
} 